<?php

namespace app\shop\controller\user;

use app\common\library\helper;
use app\common\model\user\Tag as TagModel;
use app\common\model\user\UserTag as UserTagModel;
use app\shop\controller\Controller;
use app\shop\model\order\Order as OrderModel;
use app\shop\model\user\User as UserModel;
use app\shop\model\user\Grade;
use app\common\model\user\OwnerEntry;
use app\supplier\model\supplier\Supplier as SupplierModel;

/**
 * 用户管理
 */
class User extends Controller
{
    /**
     * 商户列表
     */
    public function index($nickName = '', $gender = null, $reg_date = '', $grade_id = null)
    {
        $list = UserModel::getList($nickName, $grade_id, $reg_date, $gender = -1, $this->postData());

        foreach ($list as $key => $value){
            $god_supplier_array = json_decode($value['god_supplier_id'],true);
            $shop_supplier_name_array = (new SupplierModel())->where('shop_supplier_id','in',$god_supplier_array) -> column('name');
            $list[$key]['shop_supplier_name'] = $shop_supplier_name_array;
        }

        $GradeModel = new Grade();
        $grade = $GradeModel->getLists();
        // 所有标签
        $allTag = TagModel::getAll();
        return $this->renderSuccess('', compact('list', 'grade', 'allTag'));
    }

    public function getOwnerApplyList()
    {
        $OwnerEntry = new OwnerEntry;
        $list = $OwnerEntry->getList($this->postData());
        return $this->renderSuccess('', compact('list'));
    }



    /**
     * 删除用户
     */
    public function delete($user_id)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model && $model->setDelete()) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError($model->getError() ?: '删除失败');
    }


    /**
     * 添加用户
     */
    public function add()
    {
        $model = new UserModel;
        // 新增记录
        if ($model->add($this->request->param())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 用户充值
     */
    public function recharge($user_id, $source)
    {
        // 用户详情
        $model = UserModel::detail($user_id);

        if ($model->recharge($this->store['user']['user_name'], $source, $this->postData('params'))) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 等级改用户
     */
    public function edit($user_id)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($this->request->isGet()) {
            return $this->renderSuccess('', compact('model'));
        }
        // 修改记录
        if ($model->edit($this->postData())) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError($model->getError() ?: '修改失败');
    }

    public function tag($user_id){
        if($this->request->isGet()){
            // 用户详情
            $user = UserModel::detail($user_id);
            // 标签
            $userTag = UserTagModel::getListByUser($user_id);
            $userTag = helper::getArrayColumn($userTag, 'tag_id');
            // 所有标签
            $allTag = TagModel::getAll();
            return $this->renderSuccess('', compact('user', 'userTag' , 'allTag'));
        }
        $model = UserModel::detail($user_id);
        if($model->editTag($this->postData())){
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError($model->getError() ?: '修改失败');
    }

    /**
     * 等级改用户
     */
    public function grade($user_id)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        // 修改记录
        if ($model->updateGrade($this->postData())) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError($model->getError() ?: '修改失败');
    }


    /**
     * 导出用户列表
     * @return null
     * @Author joey
     * @date 2024/3/6 17:08
     */
    public function export()
    {
        $model = new \app\shop\model\user\User();
        return $model->exportList($this->postData(),1);
    }

    /**
     *导出用户推广员推广的订单
     * exportOrder
     * null
     * @return null
     * @Author kevin
     * @date 2024/4/9 12:03
     */
    public function exportOrder()
    {
        $model = new \app\shop\model\user\User();
        $param = $this->postData();
        $list = $this -> getUserOrderData($param);
        return $model->exportOrderList($list);
    }

    /**
     * 导出推广用户
     * exportUser
     * null
     * @return null
     * @Author kevin
     * @date 2024/4/10 11:17
     */
    public function exportUser()
    {
        $model = new \app\shop\model\user\User();
        $param = $this->postData();
        $list = $this -> getUserData($param);
        $xls_cell = [
            ['user_id' , '用户ID'],
            ['nickName' , '昵称'],
            ['apply_real_name' , '姓名'],
            ['apply_mobile' , '入驻手机号'],
            ['total_invite' , '邀请人数'],
            ['total_invite_money' , '邀请购物总额'],
            ['total_invite_num' , '推荐订单数量'],
            ['apply_region' , '区域'],
            ['shop_supplier_name_text' , '所属商户'],
            ['apply_create_time' , '申请时间'],

        ];
        $exp_title = '推广数据' . date('Y-m-d H:i:s');
        exportExcel($exp_title, $xls_cell, $list);
//        return $model->exportUserList($list);
    }

    public function getUserData($param){
        $UserModel = new UserModel();
        $where = [];

        if (isset($param['order_create_time']) && $param['order_create_time'] != '') {
            $sta_time = array_shift($param['order_create_time']);
            $end_time = array_pop($param['order_create_time']);
            $where[] = ['create_time','>=',strtotime($sta_time)];
            $where[] = ['create_time','<',strtotime($end_time)+24*3600];
        }

        if (isset($param['reg_golden']) && $param['reg_golden'] >0) {
            $where[] = ['is_golden','=',$param['reg_golden']];
        }

        if(isset($param['user_id']) && $param['user_id']){
            $where[] = ['referee_id','=',$param['user_id']];
        }

        if (isset($param['province_id']) && $param['province_id'] >0) {
            $where[] = ['province_id','=',$param['province_id']];
        }

        if (isset($param['city_id']) && $param['city_id'] >0) {
            $where[] = ['city_id','=',$param['city_id']];
        }


        if (isset($param['nick_name']) && $param['nick_name']) {
            $where[] = ['nickName|mobile|user_id','=',$param['nick_name']];
        }

        if (isset($param['nick_name']) && $param['nick_name']) {
            $where[] = ['nickName|mobile|user_id','like','%'.$param['nick_name'].'%'];
        }

        if (isset($param['reg_source']) && $param['reg_source']) {
            $where[] = ['reg_source','=',$param['nick_name']];
        }

        if (isset($param['shop_supplier_id']) && $param['shop_supplier_id']) {
            $where[] = ['god_supplier_id', 'like', '%"' .$param['shop_supplier_id']. '"%'];
        }

        $list = $UserModel -> where($where) -> select();
        foreach ($list as $key => $value){
            $god_supplier_array = json_decode($value['god_supplier_id'],true);
            $shop_supplier_name_array = (new SupplierModel())->where('shop_supplier_id','in',$god_supplier_array) -> column('name');
            $list[$key]['shop_supplier_name_text'] = implode(',', $shop_supplier_name_array);
            $list[$key]['apply_real_name'] = $value['agent_apply']['real_name'];
            $list[$key]['apply_mobile'] = $value['agent_apply']['mobile'];
            $list[$key]['apply_region'] = $value['agent_apply']['region'];
            $list[$key]['apply_create_time'] = $value['agent_apply']['create_time'];

        }


        return $list;
    }


    /**
     *获取推广员推广订单
     * getUserOrderData
     * @param $param
     * array
     * @return array
     * @Author kevin
     * @date 2024/4/9 12:04
     */
    public function getUserOrderData($param){

        $UserModel = new UserModel();
        $OrderModel = new OrderModel();

        $where = [];
        if (isset($param['province_id']) && $param['province_id'] >0) {
            $where[] = ['province_id','=',$param['province_id']];
        }

        if (isset($param['city_id']) && $param['city_id'] >0) {
            $where[] = ['city_id','=',$param['city_id']];
        }


        if (isset($param['nick_name']) && $param['nick_name']) {
            $where[] = ['nickName|mobile|user_id','like','%'.$param['nick_name'].'%'];
        }

        if (isset($param['reg_source']) && $param['reg_source']) {
            $where[] = ['reg_source','=',$param['reg_source']];
        }

        if (isset($param['shop_supplier_id']) && $param['shop_supplier_id']) {
            $where[] = ['god_supplier_id', 'like', '%"' .$param['shop_supplier_id']. '"%'];
        }

        $where[] = ['is_golden','=',1];
        $where[] = ['is_delete','=',0];

        //金牌会员id集合
        $golden_user = $UserModel -> where($where) ->  column('nickName,mobile','user_id');

        $where = [];
        //搜索时间段
        if (isset($param['order_create_time']) && $param['order_create_time'] != '') {
            $sta_time = array_shift($param['order_create_time']);
            $end_time = array_pop($param['order_create_time']);
            $where[] = ['a.create_time','>=',strtotime($sta_time)];
            $where[] = ['a.create_time','<',strtotime($end_time)+24*3600];
        }



        foreach ($golden_user as $k => $v){
            $map_u = $where;
            $map_u[] = ['a.referee_id','=',$k];
            $golden_user[$k]['total_invite'] = $UserModel-> alias('a') -> where($map_u) -> count();
            unset($map_u);
            $golden_user_ids[] = $k;
        }


        $map = [];
        $map[] = ['referee_id','in',$golden_user_ids];
        $user_ids = $UserModel -> where($map) -> column('user_id');


        $where[] = ['a.user_id','in',$user_ids];
        $where[] = ['a.pay_status','=',20];

        $field = 'a.pay_price,a.user_id,a.total_price,a.order_price,a.create_time,a.order_status,a.order_source,a.pay_status,a.delivery_status,a.receipt_status,a.assemble_status,a.delivery_type,u.referee_id';
        $list = $OrderModel
            -> alias('a')
            -> leftjoin('user u','u.user_id = a.user_id')
            -> where($where)
            -> field($field)
            -> order('order_id asc')
            -> select();
        $array = [];

        //用户订单数的统计
        foreach ($list as $value){
            if(isset($array[$value['user_id']])){
                $array[$value['user_id']]['order_price']  += $value['pay_price'];//非首单金额
                $array[$value['user_id']]['total_order_price']  += $value['pay_price'];//订单总额

                $array[$value['user_id']]['order_nums'] += 1;;//非首单总单数
                $array[$value['user_id']]['total_order_nums'] += 1;//总单数

                if($value['delivery_type']['value'] == 10){ //配送员配送的订单  （kevin 2024/5/8）
                    $array[$value['user_id']]['delivery_price'] += $value['pay_price']; //配送金额
                    $array[$value['user_id']]['delivery_order_num'] += 1; //配送单数
                }else{
                    $array[$value['user_id']]['delivery_price'] = 0; //配送金额
                    $array[$value['user_id']]['delivery_order_num'] = 0; //配送单数
                }

            }else{

                if($value['delivery_type']['value'] == 10){ //配送员配送的订单  （kevin 2024/5/8）
                    $array[$value['user_id']]['delivery_price'] = $value['pay_price']; //配送金额
                    $array[$value['user_id']]['delivery_order_num'] = 1; //配送单数
                }else{
                    $array[$value['user_id']]['delivery_price'] = 0; //配送金额
                    $array[$value['user_id']]['delivery_order_num'] = 0; //配送单数
                }

                $array[$value['user_id']]['user_id'] = $value['user_id'];
                $array[$value['user_id']]['referee_id'] = $value['referee_id'];
                $array[$value['user_id']]['first_price'] = $value['pay_price']; //首单金额
                $array[$value['user_id']]['order_price']  = 0;
                $array[$value['user_id']]['total_order_price'] = $value['pay_price'];

                $array[$value['user_id']]['order_nums'] = 0;
                $array[$value['user_id']]['first_num'] = 1; //首单单数
                $array[$value['user_id']]['total_order_nums'] = 1;

            }
        }


        $list = [];
        $referee_id_array = []; //这些订单的推广员
        foreach ($array as $k1 => $v1){
            if(!in_array($v1['referee_id'],$referee_id_array)){
                $referee_id_array[] = $v1['referee_id'];
            }

            if(isset($list[$v1['referee_id']])){
                $list[$v1['referee_id']]['total_order_price'] += $v1['total_order_price'];
                $list[$v1['referee_id']]['order_price'] += $v1['order_price'];
                $list[$v1['referee_id']]['first_price'] += $v1['first_price'];

                $list[$v1['referee_id']]['order_nums'] += $v1['order_nums'];
                $list[$v1['referee_id']]['first_num'] += $v1['first_num'];
                $list[$v1['referee_id']]['total_order_nums'] += $v1['total_order_nums'];

                $list[$v1['referee_id']]['delivery_price'] += $v1['delivery_price'];
                $list[$v1['referee_id']]['delivery_order_num'] += $v1['delivery_order_num'];

            }else{
                $user_data =  $golden_user[$v1['referee_id']]??[];
                $v1['nickName'] = $user_data['nickName'];
                $v1['mobile'] = $user_data['mobile'];
                $v1['total_invite'] = $user_data['total_invite'];
                $v1['user_id'] = $v1['referee_id'];
                $list[$v1['referee_id']] = $v1;
            }

        }

        foreach ($golden_user_ids as $k2 => $v2){
            if(!in_array($v2,$referee_id_array)){
                $user_data =  $golden_user[$v2]??[];
                $list[$v2]['user_id'] = $v2;
                $list[$v2]['referee_id'] = $user_data['referee_id']??'';
                $list[$v2]['nickName'] = $user_data['nickName']??'';
                $list[$v2]['mobile'] = $user_data['mobile']??'';
                $list[$v2]['total_invite'] = $user_data['total_invite']??0;
                $list[$v2]['total_order_price'] = 0;
                $list[$v2]['order_price'] = 0;
                $list[$v2]['first_price'] = 0;
                $list[$v2]['order_nums'] = 0;
                $list[$v2]['first_num'] = 0;
                $list[$v2]['total_order_nums'] = 0;

                $list[$v2]['delivery_price'] = 0;
                $list[$v2]['delivery_order_num'] = 0;
            }
        }
        $list = array_values($list);
        sort($list);
        return $list;
    }
}
